package study.thread.sync;


/*
 * 下面的例子描述线程干扰的问题(引出线程同步)：
 * 1.银行账户类有两个方法，存款deposit和取款withdraw；
 * 2.定义存款线程和取款线程，存款线程每次存一百，取款线程每次取一百，各运行10万次；
 */
public class BankAccount {
	
	private int number;
	
	//余额
	private int  balance;
	
	public int getBalance() {
		return balance;
	}

	public BankAccount(int number,int balance) {
		this.number = number;
		this.balance = balance;
	}
	
	//存款
	public void deposit(int amount) {
		this.balance += amount;
	}
	
	//取款
	public void withdraw(int amount) {
		this.balance -= amount;
	}
	
	public static void main(String[] args) throws InterruptedException {
		BankAccount account = new BankAccount(1,1000);
		
		Thread t1 = new Thread(new Depositor(account,100),"Depositor");
		Thread t2 = new Thread(new Withdraw(account,100),"Withdraw");
		
		t1.start();
		t2.start();
		
		t1.join();
		t2.join();
		
		System.out.println(account.balance);
	}
	
	
	//静态存款内部类
	static class Depositor implements Runnable {
		BankAccount account;
		int amount;
		
		public Depositor(BankAccount account,int amount) {
			this.account = account;
			this.amount = amount;
		}
		
		public void run() {
			for (int i = 0; i < 100000; i++) {
				account.deposit(amount);
			}
		}
	}
	
	static class Withdraw implements Runnable {
		BankAccount account;
		int amount;
		
		public Withdraw(BankAccount account,int amount) {
			this.account = account;
			this.amount = amount;
		}
		
		public void run() {
			for (int i = 0; i < 100000; i++) {
				account.withdraw(amount);
			}
		}
	}
	
}
